package msgtunnel

import (
	"fronter/msgproto"

	"github.com/gorilla/websocket"
	"github.com/sirupsen/logrus"
	"google.golang.org/protobuf/proto"
)

type wsClient struct {
	conn *websocket.Conn
}

func (c wsClient) handleMsgFromClient() {
	for {
		mt, message, err := c.conn.ReadMessage()
		if err != nil {
			logrus.Errorln("read:", err)
			break
		}
		logrus.Debugln("recv: %s", message)
		//读取成功，解包处理
		go c.handleRequest(mt, message)
	}
}

func (c wsClient) handleRequest(mt int, req_buffer []byte) {
	var transPack msgproto.TransPack
	//logrus.Infoln()
	proto.Unmarshal(req_buffer, &transPack)
	transPack.Rescode = 200
	cbfunc, iscbFind := reqHandleFunc[transPack.ProtoName]
	if !iscbFind {
		logrus.Errorln("can't find cb func to handle:", transPack.ProtoName)
		transPack.Package = []byte{}
		transPack.Rescode = 504
		return
	}
	res_proto := cbfunc(req_buffer) //直接交给函数处理
	res_buffer, _ := proto.Marshal(res_proto)
	transPack.ProtoName = string(res_proto.ProtoReflect().Descriptor().FullName())
	transPack.Package = res_buffer //填充回包
	transPack_buffer, _ := proto.Marshal(&transPack)

	err := c.conn.WriteMessage(mt, transPack_buffer) //回包给客户端
	if err != nil {
		logrus.Error("write to ws ", c.conn.RemoteAddr().String(), " failed! err:", err.Error())
		return
	}
}
